import requests class TestMain: def test(self): r = requests.get("http://www.baidu.com") # get请求百度首页 print("访问百度首页的状态码、cookie、登录状态:", r.status_code, r.cookies, r.ok) # 打印响应码 # 将get请求的响应内容写入到项目文件夹下的text.txt(若文件不存在则新建文件) with open("text.txt", 'w', encoding='utf-8') as f: f.write(r.text) # 读取text.txt-读取部分行 with open('F:\/cs_auto\/untitled1\/text.txt') as file_open: # 完整目录等同于"text.txt" print("以下只打印第一行:") for i in range(1): print(file_open.readline()) # 不需要file_open.close(),因为关键字with在我们不再需要使用文件的时候将其关闭。 # 读取text.txt-读取整个文件 with open('text.txt') as file_open: print("以下打印文件的全部内容:") print(file_open.read()) # 读取text.txt-按行读取文件内容 with open('text.txt') as file_open: print("以下按行读取并打印文件的全部内容:") for content in file_open: print(content.rstrip()) # 不调用rstrip()函数的话,会在每行后面多打印一个空行if __name__ == '__main__': print("this is main method") TestMain.test('self')
|